// /services/DietService.ts

import http from '@ohos.net.http';
import { DietSuggestionRequest, DietSuggestionResponse } from '../models/DietModels';
import { AppConfig } from '../common/config';
import UserSessionManager from '../common/UserSession';
import hilog from '@ohos.hilog';

const DOMAIN = 0xFF00;
const TAG = 'DietService';

class DietService {
  private readonly BASE_URL = AppConfig.API_BASE_URL;

  /**
   * 获取饮食建议
   * @param days 分析最近多少天的数据，默认7天
   */
  async getDietSuggestion(days: number = 7): Promise<DietSuggestionResponse> {
    const url = `${this.BASE_URL}/api/diet/suggestion/`;
    const token = UserSessionManager.getToken();

    hilog.info(DOMAIN, TAG, `发送饮食建议请求到: ${url}, days: ${days}`);

    if (!token) {
      hilog.warn(DOMAIN, TAG, '未找到token，无法获取饮食建议');
      return {
        code: 401,
        message: '用户未登录',
        data: null
      };
    }

    const httpRequest = http.createHttp();
    try {
      const requestBody: DietSuggestionRequest = { days };

      const response = await httpRequest.request(url, {
        method: http.RequestMethod.POST,
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Token ${token}`
        },
        extraData: JSON.stringify(requestBody)
      });

      hilog.info(DOMAIN, TAG, `饮食建议响应码: ${response.responseCode}`);

      if (response.responseCode === 200) {
        const result: DietSuggestionResponse = JSON.parse(response.result as string);
        hilog.info(DOMAIN, TAG, `饮食建议获取成功，建议长度: ${result.data?.suggestion?.length || 0}`);
        return result;
      } else {
        hilog.error(DOMAIN, TAG, `获取饮食建议失败，HTTP状态码: ${response.responseCode}`);
        return {
          code: response.responseCode,
          message: `请求失败 (HTTP ${response.responseCode})`,
          data: null
        };
      }
    } catch (error) {
      hilog.error(DOMAIN, TAG, `获取饮食建议失败: ${error instanceof Error ? error.message : String(error)}`);
      return {
        code: -1,
        message: '网络请求失败，请检查网络连接',
        data: null
      };
    } finally {
      httpRequest.destroy();
    }
  }
}

// 导出单例
export const dietService = new DietService();
